# use a computer to view your phone camera
# 电脑打开手机摄像头，手机上需要提前装好一个叫IP摄像头的APP
# 装好之后配置用户名和密码，连接时保证手机和电脑在同一局域网中

import cv2
import dlib
from PIL import Image
import pathlib
import os , sys
import time
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
cv2.namedWindow("camera", 1)
# open ip camera
video = "http://admin:224114@192.168.0.108:8081/video"
capture =   cv2.VideoCapture(0,cv2.CAP_DSHOW)
cwidth= 1280 #宽
chight= 720 #高
capture.set(3,cwidth)
capture.set(4,chight)
# width= 295 #宽
# hight= 413 #高
width= 390 #宽
hight= 567 #高
p=0.30 #上下比例
w=0.2 #扩展比例
def save(img,filepath,x1,y1,x2,y2):
    crop_img = img[y2:y1,x1:x2] 
    print(f"size:{x2-x1},{y1-y2}")
    filepath=str(f"{root}/img/{int(time.time())}.jpg")
    try:
        res = cv2.resize(crop_img,(width, hight), interpolation = cv2.INTER_CUBIC)
        cv2.imwrite(filepath,res)
        Image.open(filepath).save(filepath,None,dpi=(300.0,300.0))
        cv2.imshow("image", crop_img)
    except :
        res = None
        pass
# visualize inspection results
def show_detection(image, faces):
    img=image
    if(len(faces)!=0):
        for (i,face) in enumerate(faces):
            cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 128, 0), 1)
            x=int((face.right()-face.left())*w)
            y2= int((face.bottom()-face.top())*w)
            y1=int(x+face.bottom()-(hight*(face.right()-face.left()+2*x)/width))
            x1=face.left()-x
            x2=face.right()+x
            ht=(hight*(face.right()-face.left()+x+x))/width
            y1=int(face.bottom()+ht*p)
            y2=int(y1-ht)
            cv2.rectangle(img, (x1, y1), (x2,y2), (0, 0, 255), 1)
        return (x1,x2,y1,y2)
    else:
        return (-1,0,0,0)


detector = dlib.get_frontal_face_detector()

while True:
    image=None
    ret, frame = capture.read()
    if(ret):
        image1=frame
        image2=cv2.resize(frame,(int(cwidth/2), int(chight/2)))
    gray_frame = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
    faces=detector(gray_frame, 1)
    (x1_,x2_,y1_,y2_)=show_detection(image2, faces)
    if(x1_ != -1):
        (x1,x2,y1,y2)=(x1_,x2_,y1_,y2_)
    

    cv2.imshow("object detection", image2)
    k=cv2.waitKey(20) & 0xFF
    if   k == ord('q'):
        break
    if k == ord('s'):
        save(image1,"filepath",x1*2,y1*2,x2*2,y2*2)
        print("save")
    if k == ord('j'):
        w=w+0.025
        print(f"w:{w} p:{p}")
    if k == ord('l'):
        w=w-0.025   
        print(f"w:{w} p:{p}")
    if k == ord('k'):
        p=p+0.025
        print(f"w:{w} p:{p}")
    if k == ord('i'):
        p=p-0.025  
        print(f"w:{w} p:{p}")
capture.release()
cv2.destroyAllWindows()
